package com.zhouyibike.uu.ui.activity.mywallet;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Vibrator;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.CaptureView2;
import com.zhouyibike.uu.utils.Base64Utils;
import com.zhouyibike.uu.utils.RSAUtils;
import com.zhouyibike.uu.utils.Util;
import com.zhouyibike.uu.zxing.CameraManager;
import com.zhouyibike.uu.zxing.DecodeListener;
import com.zhouyibike.uu.zxing.DecodeThread;
import com.zhouyibike.uu.zxing.LuminanceSource;
import com.zhouyibike.uu.zxing.PlanarYUVLuminanceSource;
import com.zhouyibike.uu.zxing.PreviewFrameShotListener;
import com.zhouyibike.uu.zxing.RGBLuminanceSource;
import com.zhouyibike.uu.zxing.Size;

import java.security.PrivateKey;
import java.security.PublicKey;

public class SaomafukuanActivity extends BaseActivity implements SurfaceHolder.Callback, DecodeListener, PreviewFrameShotListener {
    private CameraManager mCameraManager;
    private DecodeThread mDecodeThread;
    private Rect previewFrameRect = null;
    private SurfaceView previewSv;
    private CaptureView2 captureView;
    private boolean isDecoding = false;
    private static final long SCAN_PERIOD = 100000;
    private static final long VIBRATE_DURATION = 200L;
    private String shoukuanname = "";
    private String shoukuanphone = "";
    private String shoukuanpicurl = "";
    /* 密钥内容 base64 code */
    private static String PUCLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrINgjK0/MQLHrFCS9E+VjVWAS L6RG8mY+PuvuUGuaRCGNupp39qHgBC1Bzf+eSGLDrWSiYti8b1cvIgvJWiCFDGaN wzVMs/tSL8QIK1jYLt/vMr4c8O+mmxWmU9hqHLBZnpnslf8ik7AR9ppkrYHuPBxl PH0y2e7utbnAYvkoZwIDAQAB";
    private static String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKsg2CMrT8xAsesU JL0T5WNVYBIvpEbyZj4+6+5Qa5pEIY26mnf2oeAELUHN/55IYsOtZKJi2LxvVy8i C8laIIUMZo3DNUyz+1IvxAgrWNgu3+8yvhzw76abFaZT2GocsFmemeyV/yKTsBH2 mmStge48HGU8fTLZ7u61ucBi+ShnAgMBAAECgYEAmVdL9W+pCIhsJQ6ewQKkCLeG 56TjGmO4tEwjkx9i3A/y1RIBuj843AhCGXYieE26mka0J0JVnbxTLjveveVRvw78 m1VoMuP9zddV4xC4q2kL+V683i1BTximkre8yqAVMfQr1EE6LNIlfU8XbyEHCv1d 7DhneRZEu+u7sH6SrRkCQQDe7HPlQGIp8PFfK7+MAaKszOonIKlgUeHsiZvPbpR3 gwWbz25iEoRFevqlEBx+/Z7/+6zL5lVm0dlvm//r2bkzAkEAxIT+WMBl+xHhmv1d jHziyYfBcUyQoLnkmc6SNlTs/oNVKh4AlKERLi/cv67zkevWp6Dqj8bv8WUHN6vT KChb/QJAOywgh1XTuLZQG6cNLSix+ZRbAw/UZdDWW2cbiLAdkKuirX0eG8I2ggrm xTHFnp/LuL8hWu5E9Qn24X1TLVOZqQJAJiOldTYJ1Ls4rKrFcBGAthoJueJhI0BQ lGUZzT+YKyDz81OVS0MjIXKahfz/Om+p3iiFvVefk5rG1tAbD+0dRQJATKPCyHwY HWyqrEGrVsfigY6TuRDG/3s22ikjv4UQZ5227i+TwcJT3e9d3yRNm3rPm/TjK37s LSgxtsbrfSuGwg==";
    private TextView mBtnTitle;
    private ImageView iv_capture_openlight;
    private boolean kaideng = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saomafukuan);
        initcamera();
        initview();
    }

    private void initview() {
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        iv_capture_openlight = (ImageView) findViewById(R.id.iv_capture_openlight);
        mBtnTitle.setText("扫描");
        iv_capture_openlight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (kaideng) {
                    mCameraManager.openlight();
                } else {
                    mCameraManager.closelight();
                }
                kaideng = !kaideng;
            }
        });
    }

    private void initcamera() {
        previewSv = (SurfaceView) findViewById(R.id.sv_preview);
        captureView = (CaptureView2) findViewById(R.id.cv_capture);
        previewSv.getHolder().addCallback(this);
        mCameraManager = new CameraManager(this);
        mCameraManager.setPreviewFrameShotListener(this);
    }

    ///////////////以下全是扫码内容
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mCameraManager.initCamera(holder);
        if (!mCameraManager.isCameraAvailable()) {
            Toast.makeText(SaomafukuanActivity.this, "摄像头不可以用", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mCameraManager.startPreview();
        if (!isDecoding) {
            mCameraManager.requestPreviewFrameShot();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        try {
            mCameraManager.stopPreview();
            if (mDecodeThread != null) {
                mDecodeThread.cancel();
            }
            mCameraManager.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onPreviewFrame(byte[] data, Size dataSize) {
        if (mDecodeThread != null) {
            mDecodeThread.cancel();
        }
        if (previewFrameRect == null) {
            previewFrameRect = mCameraManager.getPreviewFrameRect(captureView.getFrameRect(), Util.dp2px(this, 48));
        }
        PlanarYUVLuminanceSource luminanceSource = new PlanarYUVLuminanceSource(data, dataSize, previewFrameRect);
        mDecodeThread = new DecodeThread(luminanceSource, SaomafukuanActivity.this);
        isDecoding = true;
        mDecodeThread.execute();
    }

    @Override
    public void onDecodeSuccess(Result result, LuminanceSource source, Bitmap bitmap) {
        try {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
            isDecoding = false;
            if (bitmap.getWidth() > 100 || bitmap.getHeight() > 100) {
                Matrix matrix = new Matrix();
                matrix.postScale(100f / bitmap.getWidth(), 100f / bitmap.getHeight());
                Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                bitmap = resizeBmp;
            }
            String resultString = result.getText();
//            String msg = resultString.substring(resultString.length() - 10);
//            devId=msg;
//            getMac(msg);
            String decryptStr = "";
            try {
                PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
                PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
                byte[] decryptByte = RSAUtils.decryptByPrivateKey(Base64Utils.decode(resultString), privateKey);
                decryptStr = new String(decryptByte);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (decryptStr.startsWith("zy")) {
                shoukuanphone = decryptStr.split("@")[1];
                shoukuanname = decryptStr.split("@")[2];
                shoukuanpicurl = decryptStr.split("@")[3];
                saomiaohou();
            } else {
                toastShow("未能识别此二维码,请退出重新扫描");
                isDecoding = false;
                mCameraManager.requestPreviewFrameShot();
            }
        } catch (Exception e) {
            toastShow("扫描失败,请退出重新扫描");
        } finally {

        }
        //  toastShow(resultString);
//        Log.e( "onDecodeSuccess:",resultString);
    }

    @Override
    public void onDecodeFailed(LuminanceSource source) {
        if (source instanceof RGBLuminanceSource) {
            //    Toast.makeText(CaptureActivity.this, R.string.capture_decode_failed, Toast.LENGTH_SHORT).show();
        }
        isDecoding = false;
        mCameraManager.requestPreviewFrameShot();
    }

    @Override
    public void foundPossibleResultPoint(ResultPoint point) {
        captureView.addPossibleResultPoint(point);
    }

    private void saomiaohou() {
        if (shoukuanname.equals("zy") || shoukuanphone.equals("zy")) {
            toastShow("二维码有误");
            finish();
        } else if (shoukuanphone.equals(preferences.getString("mobile","zy"))) {
            toastShow("无法和自己的账号交易翼券");
            finish();
        } else {
            Intent intent = new Intent(this, SaomiaoSuccessfukuanActivity.class);
            intent.putExtra("shoukuanphone", shoukuanphone);
            intent.putExtra("shoukuanname", shoukuanname);
            intent.putExtra("shoukuanpicurl", shoukuanpicurl);
            startActivity(intent);
            finish();
        }

    }
}
